<template>
  <view class="team-schedule-table">
    <!-- 顶部标题 -->
    <view class="header">
      <!-- 左侧月份选择 -->
      <view class="month-select" @click="openMonthPicker">
        <u-icon name="calendar" color="#0195FF" size="22"></u-icon>
        <text>{{ currentMonth }}</text>
      </view>

      <!-- 中间部门选择 -->
      <view class="bumeng-title" style="margin-left: 16rpx;" @click="cascaderShow = true">
        <text>{{ bumentitle || '选择考勤组' }}</text>
      </view>

      <!-- 右侧搜索框 -->
      <view class="search-wrap">
        <up-input v-model="searchName" @update:modelValue="searchchange" style="height: 20rpx;" placeholder="请输入姓名"
          shape="circle"></up-input>
      </view>
    </view>

    <!-- 表格部分 -->
    <view class="table-container">
      <!-- 左侧姓名列 -->
      <view class="table-left">
        <view class="table-row table-header name-header">
          <text>姓名</text>
        </view>

        <view class="table-row name-row" v-for="user in groupedSchedule" :key="user.id"
          :class="{ 'selected-row': selectedUserId === user.id }">
          <view class="name-wrap">
            <view class="avatar-default">{{ user.name.slice(0, 1) }}</view>
            <text class="user-name">{{ user.name }}</text>
          </view>
        </view>
      </view>

      <!-- 右侧日期滚动部分 -->
      <scroll-view scroll-x class="table-right" scroll-with-animation>
        <view class="table">
          <!-- 日期头 -->
          <view class="table-row table-header">
            <view class="cell date-cell" v-for="day in dateList" :key="day.date"
              :class="{ today: day.date === todayStr }">
              <view class="date">{{ day.day }}</view>
              <view class="week">{{ day.week }}</view>
            </view>
            <view class="cell attendance-header-cell" >
              <text>出勤天数</text>
            </view>
          </view>

          <!-- 员工数据 -->
          <view class="table-row" v-for="user in groupedSchedule" :key="user.id">
            <view class="cell date-cell" v-for="day in dateList" :key="day.date"
              :class="{ today: day.date === todayStr }" @click="openShiftDetail(user, day)">
              <view class="shift morning" :class="getShiftClass(user.shifts[day.date]?.上午)">
                {{ formatType(user.shifts[day.date]?.上午) }}
              </view>
              <view class="shift afternoon" :class="getShiftClass(user.shifts[day.date]?.下午)">
                {{ formatType(user.shifts[day.date]?.下午) }}
              </view>
            </view>
            
            <view class="cell attendance-cell" :class="{ 'selected-row': selectedUserId === user.id }">
              <text>{{ user.attendanceDays.toFixed(1) + '天'  || '0.0' }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 空数据 -->
    <view v-if="groupedSchedule.length === 0" class="empty">
      <image src="@/static/attcemannt/tdpb.png" class="empty-img" />
      <text class="empty-text">暂无排班数据</text>
    </view>

    <up-datetime-picker title="选择月份" :show="datetimeShow" v-model="datetimeValue" mode="year-month"
      @cancel="datetimeShow = false" @close="datetimeShow = false"
      @confirm="handleDatetimeConfirm"></up-datetime-picker>

    <up-cascader 	headerDirection="column" :optionsCols="1" v-model:show="cascaderShow" v-model="cascaderValue" :data="setgroupList" value-key="id"
      label-key="group_name" children-key="children" @confirm="handleCascaderConfirm"></up-cascader>
  </view>
</template>

<script>
import { useUserStore } from '@/pinia-store/user';
import { mapStores } from 'pinia';
import { paibanRecord } from "@/apis/Attcemannt/index";
export default {
  props: {
    organizationList: {
      type: Array,
      default: () => {
        return []
      }
    },
    setgroupList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    const now = new Date();
    return {
      currentMonth: "",
      dateList: [],
      scheduleData: [],
      groupedSchedule: [],
      todayStr: new Date().toISOString().slice(0, 10),
      datetimeShow: false,
      datetimeValue: Date.now(),
      selectedYear: now.getFullYear(),
      selectedMonth: now.getMonth() + 1,
      cascaderShow: false,
      cascaderValue: '',
      user: {},
      bumentitle: '',
      selectedCell: {
        userId: null,
        date: null
      },
      selectedUserId: null,
      searchName: '',      // 绑定输入框
      selectedUserId: null,
      valuesid: ''
    };
  },
  computed: {
    ...mapStores(useUserStore),
    filteredSchedule () {
      if (!this.searchName) {
        return this.groupedSchedule;
      }
      // 根据姓名模糊匹配
      return this.groupedSchedule.filter(user =>
        user.name.includes(this.searchName)
      );
    },
  },
  created () {
    this.user = this.userStore.user ? this.userStore.user : JSON.parse(uni.getStorageSync('user'))?.user
    this.initMonth();
    this.generateDateList();
  },
  methods: {
    initMonth () {
      const now = new Date();
      this.currentMonth = `${now.getFullYear()}-${now.getMonth() + 1}`;
    },
    generateDateList (year = this.selectedYear, month = this.selectedMonth) {
      const days = new Date(year, month, 0).getDate();
      const weekMap = ["日", "一", "二", "三", "四", "五", "六"];
      this.dateList = Array.from({ length: days }, (_, i) => {
        const d = new Date(year, month - 1, i + 1);
        const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(
          i + 1
        ).padStart(2, "0")}`;
        return {
          day: i + 1,
          date: dateStr,
          week: "周" + weekMap[d.getDay()],
        };
      });
    },

    async loadSchedule () {
      uni.showLoading({ title: '加载中...' });
      try {
        let res = await paibanRecord({
          group_id: this.valuesid,
          page: 1,
          row: 6000,
          worker_name: this.searchName,
          year_month: this.currentMonth
        })
        if (res.status == 1) {
          uni.hideLoading();
          const exampleData = res.data;
          this.scheduleData = exampleData;
          this.groupDataByUser();
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.msg || '获取失败',
            icon: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '获取失败',
          icon: 'error',
          duration: 2000
        });
      }
    },
    groupDataByUser () {
      const grouped = {};
      this.scheduleData.forEach((item) => {
        if (!grouped[item.worker_id]) {
          grouped[item.worker_id] = {
            id: item.worker_id,
            name: item.worker_name,
            shifts: {},
            attendanceDays: 0 // 初始化出勤天数
          };
        }
        if (!grouped[item.worker_id].shifts[item.clock_date]) {
          grouped[item.worker_id].shifts[item.clock_date] = {};
        }
        grouped[item.worker_id].shifts[item.clock_date][item.time_type] = item.kaoqin_type;
      });

      // 计算每个员工的出勤天数
      Object.values(grouped).forEach(user => {
        user.attendanceDays = this.calculateAttendanceDays(user.id);
      });

      this.groupedSchedule = Object.values(grouped);
    },

    formatType (type) {
      const map = {
        "/": "出勤",
        T: "调休",
        "○": "事假",
        "╳": "旷工",
        G: "公休",
        "□": "出差",
        "Ｎ": "年假",
        H: "婚假",
        S: "丧假",
        "陪": "陪产假",
        "产": "产假",
        "△": "病假",
        "补": "补卡",
        "-": "未入职",
        "离": "离职",
      };
      return map[type] || "";
    },
    getShiftClass (type) {
      const map = {
        "/": "attend",
        T: "adjust",
        "○": "personal",
        "╳": "absent",
        G: "rest",
        "□": "trip",
        "Ｎ": "annual",
        H: "marriage",
        S: "funeral",
        "陪": "paternity",
        "产": "maternity",
        "△": "sick",
        "补": "reissue",
        "-": "notin",
        "离": "left",
      };
      return map[type] || "";
    },
    openMonthPicker () {
      this.datetimeShow = true;
    },
    handleDatetimeConfirm (e) {
      const date = new Date(e.value);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.currentMonth = `${year}-${month}`;
      this.selectedYear = year;
      this.selectedMonth = month;
      this.generateDateList();

      this.datetimeShow = false;

      if (!this.bumentitle) {
        uni.showToast({
          title: '请选择考勤组',
          icon: 'error',
          duration: 2000
        });
        return
      }
      this.loadSchedule();
    },
    handleCascaderConfirm (value) {
      this.bumentitle = value.items[0].group_name;
      this.valuesid = value.values[0]
      this.loadSchedule();
    },
    openShiftDetail (user, day) {
      this.selectedUserId = user.id;
    },
    searchchange (value) {
      if (!this.bumentitle) {
        uni.showToast({
          title: '请选择考勤组',
          icon: 'error',
          duration: 2000
        });
        return;
      }

      this.searchName = value;
      this.loadSchedule();
    },
    // 计算单个员工的出勤天数
    calculateAttendanceDays(workerId) {
      const workerData = this.scheduleData.filter(item => item.worker_id === workerId);
      const dates = {};

      workerData.forEach(item => {
        const date = item.clock_date;
        if (!dates[date]) dates[date] = { morning: false, afternoon: false };
        if (item.time_type === '上午') dates[date].morning = item.kaoqin_type === '/';
        if (item.time_type === '下午') dates[date].afternoon = item.kaoqin_type === '/';
      });

      let totalDays = 0;
      Object.values(dates).forEach(({ morning, afternoon }) => {
        if (morning && afternoon) totalDays += 1;
        else if (morning || afternoon) totalDays += 0.5;
      });

      return totalDays;
    }
  },
};
</script>

<style lang="scss" scoped>
.team-schedule-table {
  height: auto;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12rpx 20rpx;
    background: #f9f9f9;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .month-select {
      display: flex;
      align-items: center;
      padding: 0 16rpx;
      height: 50rpx;
      background: #fff;
      border-radius: 25rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.08);
      font-size: 26rpx;
      color: #0195FF;
      cursor: pointer;

      u-icon {
        margin-right: 6rpx;
      }
    }

    .bumeng-title {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      padding: 0 16rpx;
      height: 50rpx;
      background: #fff;
      border-radius: 25rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.08);
      font-size: 26rpx;
      color: #333;
      cursor: pointer;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;

      u-icon {
        margin-left: 6rpx;
      }
    }

    .search-wrap {
      flex: 1;
      margin-left: 20rpx;

    }
  }



  --row-h: 96rpx;

  .table-container {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    // overflow: hidden;
    overflow-y: auto;
  }

  /* 左侧姓名列 */
  .table-left {
    width: 200rpx;
    background: #fff;
    border-right: 1px solid #eee;
    flex-shrink: 0;

    .table-row {
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      min-height: 120rpx;
      /* 与右侧行高一致 */
      border-bottom: 1px solid #f0f0f0;
      box-sizing: border-box;
    }

    .name-header {
      font-weight: bold;
      background: #f2f4f7;
      justify-content: center;
    }

    .name-row {

      /* 保证头像和名字垂直居中对齐 */
      .name-wrap {
        display: flex;
        align-items: center;
      }
    }

    .avatar-default {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background-color: #0195ff;
      color: #fff;
      text-align: center;
      line-height: 60rpx;
      margin-right: 12rpx;
      flex-shrink: 0;
    }

    .user-name {
      font-size: 28rpx;
      color: #333;
    }
  }

  /* 右侧可滚动日期部分 */
  .table-right {
    flex: 1;
    overflow-x: scroll;
    background: #fff;
  }

  .table {
    min-width: 1500rpx;
    box-sizing: border-box;

    .table-row {
      display: flex;
      border-bottom: 1px solid #f0f0f0;
      height: 118rpx;
      align-items: stretch;
    }

    .table-header {
      // background: #f2f4f7;
      font-weight: bold;
    }

    .date-cell {
      width: 110rpx;
      text-align: center;
      flex-shrink: 0;
      border-left: 1px solid #f0f0f0;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      /* 上下两个 shift 平分垂直空间 */
      padding: 0;
      /* 保持和左侧行高度一致 */

      .date {
        /* header 显示日期（若需要垂直居中，可适当调整） */
        font-size: 32rpx;
        margin-top: 8rpx;
      }

      .week {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 8rpx;
      }
    }

    /* 将 shift 高度设置为行高的一半，保证日期单元与姓名列高度对应 */
    .shift {
      height: calc(var(--row-h));
      line-height: calc(var(--row-h)/1.5);
      font-size: 28rpx;
      border-bottom: 1px solid #f5f5f5;
      box-sizing: border-box;
      padding: 0 6rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &.morning {
        background: #f7fcff;
      }

      &.afternoon {
        background: #fffdf7;
      }
    }

    .today {
      background-color: #e6f7ff;
    }

    /* 考勤颜色类 */
    .attend {
      color: #07c160;
    }

    .adjust {
      color: #0095ff;
    }

    .personal {
      color: #ffaa00;
    }

    .absent {
      color: #ff4d4f;
      font-weight: bold;
    }

    .rest {
      color: #999;
    }

    .trip {
      color: #5b8ff9;
    }

    .annual {
      color: #52c41a;
    }

    .marriage {
      color: #eb2f96;
    }

    .funeral {
      color: #722ed1;
    }

    .paternity {
      color: #13c2c2;
    }

    .maternity {
      color: #ff85c0;
    }

    .sick {
      color: #faad14;
    }

    .reissue {
      color: #2f54eb;
    }

    .notin {
      color: #ccc;
    }

    .left {
      color: #bfbfbf;
      text-decoration: line-through;
    }
  }

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 160rpx 20rpx;
    text-align: center;
    background-color: #fff;
    border-radius: 16rpx;
    margin-top: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .empty-img {
      width: 220rpx;
      height: 220rpx;
      opacity: 0.8;
      margin-bottom: 30rpx;
      transition: opacity 0.3s;
      border-radius: 10px;
    }

    .empty-img:hover {
      opacity: 1;
    }

    .empty-text {
      font-size: 30rpx;
      color: #6b7280;
      letter-spacing: 0.5rpx;
      font-weight: 500;
      padding: 8rpx 20rpx;
      border-radius: 8rpx;
    }
  }

  .selected-row {
    background-color: #e6f7ff !important; // 浅蓝色背景，与今日日期背景呼应
    transition: background-color 0.2s ease; // 平滑过渡
  }

  .attendance-header-cell {
    width: 110rpx; // 移动端合适宽度，不挤压日期列
    text-align: center;
    flex-shrink: 0;
    border-left: 1px solid #f0f0f0;
    background: #f2f4f7;
    font-weight: bold;
    font-size: 26rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  // 员工数据行样式
  .attendance-cell {
    width: 110rpx; // 与表头宽度一致
    text-align: center;
    flex-shrink: 0;
    border-left: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #000; // 突出显示出勤天数
    font-weight: 500;
    background: #f9fbff; // 轻微背景色，区分数据列
  }
}
</style>
